package be.sc.classicnetwork.controller.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.acegisecurity.Authentication;
import org.acegisecurity.context.SecurityContextHolder;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import be.sc.classicnetwork.model.User;
import be.sc.classicnetwork.model.UserInfo;
import be.sc.classicnetwork.util.Constant;

/**
 * ApplicationInterceptor.
 */
public class AuditInterceptor extends HandlerInterceptorAdapter {

	private LocaleResolver localeResolver;

	/**
	 * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse, java.lang.Object)
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// get the Authentication
		Authentication authentication = SecurityContextHolder.getContext()
				.getAuthentication();
		User user;

		// check anonymous access
		if (authentication.getName().equals("anonymousUser")) {
			user = User.ANONYMOUS_USER;
		} else {
			user = (User) authentication.getPrincipal();
		}

		// fill user info for logging purpose
		UserInfo userInfo = new UserInfo();
		userInfo.setRemoteAddress(request.getRemoteAddr());
		userInfo.setRemoteHost(request.getRemoteHost());
		userInfo.setRemotePort(request.getRemotePort());
		userInfo.setRemoteUser(user.getUsername());
		userInfo.setUserAgent(request.getHeader("user-agent"));
		user.setUserInfo(userInfo);

		User.setCurrentUser(user);

		// points to the right collection of cars
		request.setAttribute("cars",
				user.isInRole(Constant.ROLE_SUB_ADMIN) ? "allCars"
						: "filteredCars");

		// set the locale
		user.setLocale(localeResolver.resolveLocale(request));

		return super.preHandle(request, response, handler);
	}

	public void setLocaleResolver(LocaleResolver localeResolver) {
		this.localeResolver = localeResolver;
	}
}
